using System;
using System.Web;
using System.Web.Mvc;
using DotNetOpenAuth.OpenId.RelyingParty;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using TheBoard.Models;

[assembly: WebActivator.PreApplicationStartMethod(typeof(OpenIdAuthentication), "PreApplicationStart")]

namespace TheBoard.Models
{
    public class OpenIdAuthentication
    {
        public static void PreApplicationStart()
        {
            DynamicModuleUtility.RegisterModule(typeof(OpenIdAuthenticationModule));
        }

        public static void AuthorizeRequest(HttpContext context)
        {
            var session = DependencyResolver.Current.GetService<IOpenIdSessions>();
            if (session == null)
            {
                return;
            }

            var requestCookie = context.Request.Cookies[session.SessionCookieName];
            if (requestCookie != null)
            {
                var principal = session.TryGetPrincipal(requestCookie.Value);
                if (principal != null)
                {
                    context.User = principal;
                }
            }
        }

        public static void Authorize(IAuthenticationResponse response)
        {
            var session = DependencyResolver.Current.GetService<IOpenIdSessions>();
            if (session == null)
            {
                return;
            }

            var keyAndPrincipal = session.CreatePrincipal(response);

            session.SetPrincipal(keyAndPrincipal.Key, keyAndPrincipal.Principal);


            var cookies = HttpContext.Current.Response.Cookies;
            cookies.Remove(session.SessionCookieName);

            var cookie = new HttpCookie(session.SessionCookieName)
                             {Value = keyAndPrincipal.Key, Expires = DateTime.Now + TimeSpan.FromMinutes(20)};

            cookies.Add(cookie);
        }

        public static void UnAuthorize()
        {
            var session = DependencyResolver.Current.GetService<IOpenIdSessions>();
            if (session == null)
            {
                return;
            }

            var cookie = HttpContext.Current.Request.Cookies[session.SessionCookieName];
            if (cookie != null)
            {
                session.RemovePrincipal(cookie.Value);

                HttpContext.Current.Request.Cookies.Remove(session.SessionCookieName);
                HttpContext.Current.Response.Cookies.Remove(session.SessionCookieName);
                HttpContext.Current.Response.Cookies.Add(new HttpCookie(session.SessionCookieName){Value = "", Expires = DateTime.Now.AddDays(-1)});

                HttpContext.Current.User = null;
            }
        }
    }
}